package com.example.mapping.manage;

import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.mapping.common.exception.MappingBizException;
import com.example.mapping.constant.Constants;
import com.example.mapping.convert.DictConvert;
import com.example.mapping.domain.Dict;
import com.example.mapping.domain.Rule;
import com.example.mapping.dto.DictDto;
import com.example.mapping.dto.DictQueryDto;
import com.example.mapping.sevice.DictService;
import com.example.mapping.vo.DictVo;
import com.example.mapping.vo.RuleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Objects;

import static com.example.mapping.common.exception.MappingErrorCodeEnum.*;

/**
 * 字典Manage类
 *
 * @author baoyoujia
 */
@Component
public class DictManage {

    @Autowired
    private DictService dictService;

    @Autowired
    private DictConvert dictConvert;

    public PageDTO<DictVo> getDictByPage(DictQueryDto dictQueryDto) {
        PageDTO<Dict> pageDTO = new PageDTO<>();
        pageDTO.setCurrent(dictQueryDto.getCurrent());
        pageDTO.setSize(dictQueryDto.getSize());
        PageDTO<Dict> dictPage = dictService.page(pageDTO);
        if (CollectionUtils.isEmpty(dictPage.getRecords())) {
            return new PageDTO<>();
        }
        return dictConvert.modelPage2Vo(dictPage);
    }


    public DictVo getDict(Long id) {
        Dict dict = dictService.getById(id);
        if (Objects.isNull(dict)) {
            return new DictVo();
        }
        return dictConvert.model2Vo(dict);
    }

    public Boolean addDict(DictDto dictDto) {
        Dict dict = dictConvert.dto2Model(dictDto);
        boolean result = dictService.save(dict);
        if (!result) {
            throw new MappingBizException(ADD_DICT_ERROR);
        }
        return true;
    }

    public Boolean editDict(DictDto dictDto) {
        Dict dict = dictConvert.dto2Model(dictDto);
        boolean result = dictService.updateById(dict);
        if (!result) {
            throw new MappingBizException(EDIT_DICT_ERROR);
        }
        return true;
    }

    public Boolean delDict(Long id) {
        Dict dict = dictService.getById(id);
        dict.setSysDelete(Constants.Number.INT_2);
        boolean result = dictService.updateById(dict);
        if (!result) {
            throw new MappingBizException(DEL_DICT_ERROR);
        }
        return true;
    }
}
